import axios from "axios"
import router from "./router"
import { Loading, Message  } from 'element-ui'

let loading

//显示加载动画
function startLoading() {
    loading = Loading.service({
        lock: true,
        text: '拼命加载中...',
        background: 'rgba(0,0,0,0.7)'
    })
}

//关闭加载动画
function endLoading() {
    loading.close()
}

// 请求拦截
axios.interceptors.request.use((config) => {
    //加载动画
    startLoading();

    //设置token 请求头
    if(localStorage.eleToken){
        config.headers.Authorization = localStorage.eleToken;
    };

    return config;
}, (error) => {
    // 请求失败的处理
    return Promise.reject(error);
});

// 响应拦截
axios.interceptors.response.use((response) => {
    endLoading();
    // 处理响应数据
    return response;
}, (error) => {
    endLoading();

    //获取错误状态码
    const {status} = error.response;
    if(status == '401'){
        Message.error('token失效，请重新登陆！');
        //清除token
        localStorage.removeItem('eleToken');
        //跳转到登陆页面
        router.push('/login');
    }

    // 处理响应失败
    return Promise.reject(error);
});

export default axios